package com.aispeech.asr.apis.ssc;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.reactive.config.EnableWebFlux;

import com.aispeech.asr.apis.ssc.config.AppConfig;
import com.aispeech.asr.clib.arpc.ARpc;
import com.aispeech.jarpc.JArpc;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@SpringBootApplication
@ComponentScan("com.aispeech.asr")
@EnableWebFlux
@EnableAsync
public class SscApp implements CommandLineRunner, ApplicationListener<ContextClosedEvent> {
    @Autowired
    AppConfig config;

    public static void main(String[] args) throws IOException {
        Path tmpPath = Paths.get(System.getProperty("java.io.tmpdir"), "nio-file-upload");
        if (!tmpPath.toFile().exists())
            Files.createDirectory(tmpPath);

        System.setProperty("java.net.preferIPv4Addresses", "true"); //解决Netty DNS解析的时候，会使用AAAA记录，换取IPv6的地址
        System.setProperty("java.net.preferIPv4Stack", "true"); //解决Netty DNS解析的时候，会使用AAAA记录，换取IPv6的地址

        SpringApplication.run(SscApp.class, args);
    }

    @Override
    public void run(String... args) {
        //ARpc.initialize(2);
        try {
			JArpc.initialize();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.info("SscApp JArpc failed,...", e);
		}
        log.info("SscApp is running, ver: {}...", config.getVersion());
    }

    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        if (event.getApplicationContext().getParent() == null) {
            log.info("SscApp shutdown...");
            //ARpc.destroy();
            //JArpc.
        }
    }
}
